<?php

namespace appApi\controllers;


use appApi\components\ResultStatus;
use appApi\components\Utils;
use appApi\dao\AppApi as AppApiDao;
use Yii;


/**
 * 处理获取访问token的请求
 * @package appApi\controllers
 */
class TokenController extends BaseApiController
{
    const REQUEST_TYPE = 'token';
    /**
     * @var \app\models\AppAccess
     */
    private $appAccess;

    /**
     * 验证access_token
     * @return bool
     */
    protected function verifyToken()
    {
        $appAccess = AppApiDao::appAccessInfo($this->parameters->accessToken);
        if($appAccess == false || $appAccess->state != 1) {
            $this->sendError(ResultStatus::ACCESS_TOKEN_ERROR, 'access token错误.', true);
            Yii::error(ResultStatus::ACCESS_TOKEN_ERROR . 'access token错误., GET: ' . json_encode($_GET) . ', POST: ' . json_encode($_POST));
            return false;
        }
        $this->secretToken = $appAccess->secret_token;
        $this->appAccess = $appAccess;
        return true;
    }

    public function actionIndex()
    {
        $accessToken = Utils::createToken();
        $secretToken = Utils::createToken();
        $expiresIn = \Yii::$app->params['accessTokenExpiresIn'];
        // 保存数据
        if(AppApiDao::addAccessToken($this->appAccess->id, $accessToken, $secretToken, $expiresIn, $this->parameters->data)) {
            return $this->sendResult([
                'access_token' => $accessToken,
                'secret_token' => $secretToken,
                'expires_in' => $expiresIn,
            ]);
        } else {
            Yii::error("数据库异常, 保存授权信息异常, access_token: $accessToken, secret_token: $secretToken, expires_in: $expiresIn");
            return $this->sendError(ResultStatus::DATABASE_ERROR, '数据库异常.');
        }
    }
}